<?php
class Relation_redis extends Common_redis_model{
	public function __construct(array $params = array()) 
	{
		parent::__construct();
		$this->params=$params;
	}

    //保存用戶动态数据
	function save_dynamic_data($data = array(), $order = 'r_id', $type= 'desc', $cycle= 0, $cate_id=0)
	{
		if(!is_array($data)){
			return false;
		}

        if(!empty($cate_id)){
	        $extendstr = $order.':'.$type.':'.$cycle.':'.$cate_id;
        }else{
            $extendstr = $order.':'.$type.':'.$cycle;	
        }
        
		$redis_dynamic_key = $this->params['channel'] . ":" .$extendstr.":list";

		$this->redis->del($redis_dynamic_key);//先删除
		
        foreach($data as $dk=>$dv){
        	$score = $dv[$order];
        	unset($dv['r_id']);
        	unset($dv['r_up_count']);

			$result=$this->redis->zAdd($redis_dynamic_key, $score, json_encode($dv));//设置redis key   
        }
		
		return true;
	}

	function get_dynamic_list($order = 'r_id', $type = 'desc', $cycle = 0, $limit = 0, $offset = 10, $cate_id=0)
	{
		// 临时取消这2个参数的限制功能2016-07-07  qu zhanggui
		$type = 'desc';
		$cycle=0;
		
		if(!empty($cate_id)){
    		$extendstr = $order.':'.$type.':'.$cycle.':'.$cate_id;
        }else{
			$extendstr = $order.':'.$type.':'.$cycle;        	
        }

		$lists = $score = array();
		$key = $this->params['channel'] . ":" . $extendstr. ":list";
		
		$star 	= !empty($limit)? $limit * $offset : $limit;
		$end	= !empty($offset) ? $offset * ($limit +1)  : $offset;
		$count = (int) $this->redis->zSize($key);

		if( !empty($count)) {
			if(strtolower($type)=='desc'){
				$score	= $this->redis->zRevRange($key, $star, ($end-1), FALSE);				
			}else{
				$score	= $this->redis->ZRANGE($key, $star, ($end-1), FALSE);	
			}

			if(!empty($score)) {
				foreach($score as $key=>$val) {
					$relation_info = json_decode($val,true);
					$lists[] = $relation_info;
				}
			}
		}
		return $lists;
	}
	
}